// ========== DOM元素获取 ==========  
// 获取所有控制相关的DOM元素  

// 油门控制元素  
const throttleSlider = document.getElementById('throttle');  
const throttleValue = document.getElementById('throttle-value');  

// 刹车控制元素  
const brakeSlider = document.getElementById('brake');  
const brakeValue = document.getElementById('brake-value');  

// 方向盘控制元素  
const steeringSlider = document.getElementById('steering');  
const steeringValue = document.getElementById('steering-value');  

// 挡位控制元素  
const gearButtons = {  
    'P': document.getElementById('gear-p'),  
    'R': document.getElementById('gear-r'),  
    'NONE': document.getElementById('gear-none'),  
    'D': document.getElementById('gear-d')  
};  
const gearValue = document.getElementById('gear-value');  

// 灯光控制元素
const lightButtons = {
    'L': document.getElementById('light-L'),
    'R': document.getElementById('light-R'),
    'Harzd': document.getElementById('light-Harzd'),
    'NONE': document.getElementById('light-none')
};
const lightValue = document.getElementById('light-value');

const frontLightButtons = {
    'OFF': document.getElementById('front-light-OFF'),
    'LOW': document.getElementById('front-light-LOW'),
    'HIGH': document.getElementById('front-light-HIGH'),
    'OVERTAKING': document.getElementById('front-light-OVERTAKING'),
    'AUTO': document.getElementById('front-light-AUTO')
};
const frontLightValue = document.getElementById('front-light-value');

// 连接状态元素  
const connectionStatus = document.getElementById('connection-status');  

// 驾驶模式相关元素  
const driveMode = document.getElementById('drive-mode');  
const modeToggleBtn = document.getElementById('mode-toggle');  
const modeDescription = document.getElementById('mode-description');  

// 启用/禁用按钮  
const throttleEnable = document.getElementById('throttle-enable');  
const brakeEnable = document.getElementById('brake-enable');  
const steeringEnable = document.getElementById('steering-enable');  
const gearEnable = document.getElementById('gear-enable');
const lightEnable = document.getElementById('light-enable');
const epbEnable = document.getElementById('epb-enable');
const epbCmd = document.getElementById('epb-cmd');

// 控制容器（用于禁用时的视觉效果）  
const throttleControls = document.getElementById('throttle-controls');  
const brakeControls = document.getElementById('brake-controls');  
const steeringControls = document.getElementById('steering-controls');  
const gearControls = document.getElementById('gear-controls');
const lightControls = document.getElementById('light-controls'); 

// 获取 EPB 相关控制容器
const epbControls = document.getElementById('epb-controls');
const epbCmdControls = document.getElementById('epb-cmd-controls');



// ========== 新增：车辆状态显示元素 ==========  
//  ip和端口输入
const ipAddressInput = document.getElementById('ip-address');
const portNumberInput = document.getElementById('port-number');
const connectButton = document.getElementById('connect-button');
const resetButton = document.getElementById('reset-button');

// 底盘状态元素  
const statusSpeed = document.getElementById('status-speed');  
const statusSteeringAngle = document.getElementById('status-steering-angle');  
const statusGear = document.getElementById('status-gear');  
const statusBrakePedal = document.getElementById('status-brake-pedal');  
const statusThrottlePedal = document.getElementById('status-throttle-pedal');  

// 物理输入元素
const throttleInput = document.getElementById('throttle-input');
const brakeInput = document.getElementById('brake-input');
const steeringInput = document.getElementById('steering-input');
const gearInput = document.getElementById('gear-input');

// 程序输入元素
const throttleCommand = document.getElementById('throttle-command');
const brakeCommand = document.getElementById('brake-command');
const steeringCommand = document.getElementById('steering-command');
const gearCommand = document.getElementById('gear-command');
const gearReject = document.getElementById('gear-reject');

// 接管状态元素
const throttleOverride = document.getElementById('throttle-override');
const brakeOverride = document.getElementById('brake-override');
const steeringOverride = document.getElementById('steering-override');
const gearOverride = document.getElementById('gear-override');

// 握手状态元素  
const throttleHandshake = document.getElementById('throttle-handshake');
const brakeHandshake = document.getElementById('brake-handshake');
const steeringHandshake = document.getElementById('steering-handshake');
const gearHandshake = document.getElementById('gear-handshake');


// 控制状态元素  
const controlThrottleStatus = document.getElementById('control-throttle-status');  
const controlBrakeStatus = document.getElementById('control-brake-status');  
const controlSteeringStatus = document.getElementById('control-steering-status');  
const controlGearStatus = document.getElementById('control-gear-status');  
const controlDrivingMode = document.getElementById('control-driving-mode');  

// websocket系统状态元素  
const serverStatus = document.getElementById('server-status');  
const connectedClients = document.getElementById('connected-clients');  
const dataSequence = document.getElementById('data-sequence');  
const lastUpdate = document.getElementById('last-update');  
const panelMode = document.getElementById('panel-mode');

// 面板模式元素
const panelModeToggle = document.getElementById("panel-mode-toggle");
const panelModeText = document.getElementById("panel-mode-text");

// 连接元素
const connectToggle = document.getElementById("connection-toggle");
const connectStatusText = document.getElementById("connect-status-text");
const ipInput = document.getElementById("ip-input") ;
const ipAddr = document.getElementById("ip-address");
const portNumber = document.getElementById("port-number");


// 获取配置元素
const throttleMin = document.getElementById('throttle-min');
const throttleMax = document.getElementById('throttle-max');
const throttleStep = document.getElementById('throttle-step');
const throttleInit = document.getElementById('throttle-init');
const brakeMin = document.getElementById('brake-min');
const brakeMax = document.getElementById('brake-max');
const brakeStep = document.getElementById('brake-step');
const brakeInit = document.getElementById('brake-init');
const steeringMin = document.getElementById('steering-min');
const steeringMax = document.getElementById('steering-max');
const steeringStep = document.getElementById('steering-step');
const steeringInit = document.getElementById('steering-init');

const configSaveButten = document.getElementById('config-save-btn');


// ========== 应用状态变量 ==========  

// 默认配置
let config = null;

// 当前挡位状态（默认为NONE，与C++后端保持一致）  
let currentGear = 'NONE';

// 当前灯光状态（默认为NONE）
let currentLight = 'NONE';
let currentFrontLight = 'OFF';  // 前灯默认状态为OFF

// WebSocket连接状态  
let isConnected = false;  

// 驾驶模式状态 (false=泊车模式, true=行车模式)  
let isDrivingMode = false;  

// 各控制器的启用状态 - 默认全部禁用（安全考虑）  
let enableStates = {  
    throttle: false,    // 油门禁用  
    brake: false,       // 刹车禁用  
    steering: false,    // 方向盘禁用  
    gear: false,        // 挡位禁用
    light: false,        // 灯光禁用,
    epb: false,         // 添加 EPB 状态
    epb_cmd: false      // 添加 EPB 命令状态
};  

// 数字模式变量
let throttleNumberMode = 0;  // 油门数字模式值
let brakeNumberMode = 0;     // 刹车数字模式值
let steeringNumberMode = 0;  // 方向盘数字模式值




// 独立数字输入框功能

// 独立数字输入框功能 - 修复回车键响应
function initNumberInputMode() {
    // 油门数字输入框
    const throttleInput = document.getElementById('throttle-number');
    if (throttleInput) {
        // 回车键事件
        throttleInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseInt(this.value) || 0;
                throttleNumberMode = value;
                this.value = value; // 移除前导零
                console.log(`油门数字模式设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });

        // 移除前导零
        throttleInput.addEventListener('input', function() {
            let value = parseInt(this.value);
            if (!isNaN(value)) {
                this.value = value.toString();
            } else if (this.value === '') {
                this.value = '0';
            }
        });

        // 失去焦点时移除前导零
        throttleInput.addEventListener('blur', function() {
            let value = parseInt(this.value);
            if (isNaN(value)) {
                this.value = '0';
            } else {
                this.value = value.toString();
            }
        });
    }
    
    // 刹车数字输入框
    const brakeInput = document.getElementById('brake-number');
    if (brakeInput) {
        // 回车键事件
        brakeInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseInt(this.value) || 0;
                brakeNumberMode = value;
                this.value = value; // 移除前导零
                console.log(`刹车数字模式设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });

        // 移除前导零
        brakeInput.addEventListener('input', function() {
            let value = parseInt(this.value);
            if (!isNaN(value)) {
                this.value = value.toString();
            } else if (this.value === '') {
                this.value = '0';
            }
        });

        // 失去焦点时移除前导零
        brakeInput.addEventListener('blur', function() {
            let value = parseInt(this.value);
            if (isNaN(value)) {
                this.value = '0';
            } else {
                this.value = value.toString();
            }
        });
    }

    // 方向盘数字输入框
    const steeringInput = document.getElementById('steering-number');
    if (steeringInput) {
        // 回车键事件
        steeringInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseInt(this.value) || 0;
                steeringNumberMode = value;
                this.value = value; // 移除前导零
                console.log(`方向盘数字模式设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });

        // 移除前导零
        steeringInput.addEventListener('input', function() {
            let value = parseInt(this.value);
            if (!isNaN(value)) {
                this.value = value.toString();
            } else if (this.value === '') {
                this.value = '0';
            }
        });

        // 失去焦点时移除前导零
        steeringInput.addEventListener('blur', function() {
            let value = parseInt(this.value);
            if (isNaN(value)) {
                this.value = '0';
            } else {
                this.value = value.toString();
            }
        });
    }

    console.log('数字输入框模式已初始化 - 支持回车键直接响应');
}

function initNumberInputCmd(){
    // 油门控制值输入框
    const throttleCmdInput = document.getElementById('throttle-cmd');
    if (throttleCmdInput) {
        // 回车键事件
        throttleCmdInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseFloat(this.value) || 0.0;
                
                // 限制输入范围
                if (value < throttleMin.value) {
                    value = throttleMin.value;
                } else if (value > throttleMax.value) {
                    value = throttleMax.value;
                }
                this.value = value; 
                
                // 更新UI状态和滑杆状态
                if (!enableStates.throttle) return;  // 禁用时不响应  
                throttleValue.textContent = parseFloat(this.value).toFixed(2);  // 更新UI显示值  
                throttleSlider.value = this.value;  // 更新滑杆值
                
                console.log(`油门控制值设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });
    }

    // 刹车控制值输入框
    const brakeCmdInput = document.getElementById('brake-cmd');
    if (brakeCmdInput) {
        // 回车键事件
        brakeCmdInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseFloat(this.value) || 0.0;

                // 限制输入范围
                if (value < brakeMin.value) {
                    value = brakeMin.value;
                } else if (value > brakeMax.value) {
                    value = brakeMax.value;
                }
                this.value = value; // 移除前导零
                
                // 更新UI状态和滑杆状态
                if (!enableStates.brake) return;  // 禁用时不响应  
                brakeValue.textContent = parseFloat(this.value).toFixed(2);  // 更新UI显示值  
                brakeSlider.value = this.value;  // 更新滑杆值
                
                console.log(`刹车控制值设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });
    }

    // 方向盘控制值输入框
    const steeringCmdInput = document.getElementById('steering-cmd');
    if (steeringCmdInput) {
        // 回车键事件
        steeringCmdInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                let value = parseFloat(this.value) || 0.0;
                // 限制输入范围
                if (value < steeringMin.value) {
                    value = steeringMin.value;
                } else if (value > steeringMax.value) {
                    value = steeringMax.value;
                }
                this.value = value; // 移除前导零
                
                // 更新UI状态和滑杆状态
                if (!enableStates.steering) return;  // 禁用时不响应  
                steeringValue.textContent = parseFloat(this.value).toFixed(2);  // 更新UI显示值  
                steeringSlider.value = this.value;  // 更新滑杆值
                
                console.log(`方向盘控制值设置: ${value} (回车键触发)`);
                sendControlData();
            }
        });
    }

}

// 连接的初始状态
connectToggle.checked = false;


// 加载配置文件
function loadConfig() {
    try {
        // 直接使用全局配置
        const config = window.CONFIG;
        console.log('配置加载成功:', config);
        
    } catch (error) {
        console.error('配置加载失败:', error);
    }
}

// 页面加载完成后加载配置
document.addEventListener('DOMContentLoaded', loadConfig);

// 导出函数供外部使用
window.resetAllNumberModes = resetAllNumberModes;
window.getAllNumberModeValues = getAllNumberModeValues;
window.setNumberModeValue = setNumberModeValue;

// 切换模式后的初始化操作 （如切换控制模式，切换驾驶模式）
function switch_init(){

    enableStates['throttle'] = false;
    enableStates['brake'] = false;
    enableStates['steering'] = false;
    enableStates['gear'] = false;
    enableStates['light'] = false;
    enableStates['epb'] = false;
    enableStates['epb_cmd'] = false;

    updateControlUI('epb');
    updateControlUI('epb_cmd');
    updateControlUI('throttle');
    updateControlUI('brake');
    updateControlUI('steering');
    updateControlUI('gear');
    updateControlUI('light');

    sendControlData();      

    if (isDrivingMode){ // 行车模式
        throttleSlider.min = window.CONFIG.control.driving.throttle.defaultMin;
        throttleSlider.max = window.CONFIG.control.driving.throttle.defaultMax;
        throttleSlider.step = window.CONFIG.control.driving.throttle.defaultStep;
        throttleSlider.value = window.CONFIG.control.driving.throttle.defaultInit;
        brakeSlider.min = window.CONFIG.control.driving.brake.defaultMin;
        brakeSlider.max = window.CONFIG.control.driving.brake.defaultMax;
        brakeSlider.step = window.CONFIG.control.driving.brake.defaultStep;
        brakeSlider.value = window.CONFIG.control.driving.brake.defaultInit;
        steeringSlider.min = window.CONFIG.control.driving.steering.defaultMin;
        steeringSlider.max = window.CONFIG.control.driving.steering.defaultMax;
        steeringSlider.step = window.CONFIG.control.driving.steering.defaultStep;
        steeringSlider.value = window.CONFIG.control.driving.steering.defaultInit;

        // 将配置文件的值填入配置输入框
        throttleMin.value = window.CONFIG.control.driving.throttle.defaultMin;
        throttleMax.value = window.CONFIG.control.driving.throttle.defaultMax;
        throttleStep.value = window.CONFIG.control.driving.throttle.defaultStep;
        throttleInit.value = window.CONFIG.control.driving.throttle.defaultInit;
        brakeMin.value = window.CONFIG.control.driving.brake.defaultMin;
        brakeMax.value = window.CONFIG.control.driving.brake.defaultMax;
        brakeStep.value = window.CONFIG.control.driving.brake.defaultStep;
        brakeInit.value = window.CONFIG.control.driving.brake.defaultInit;
        steeringMin.value = window.CONFIG.control.driving.steering.defaultMin;
        steeringMax.value = window.CONFIG.control.driving.steering.defaultMax;
        steeringStep.value = window.CONFIG.control.driving.steering.defaultStep;
        steeringInit.value = window.CONFIG.control.driving.steering.defaultInit;

        throttleValue.textContent = throttleSlider.value;
        brakeValue.textContent = brakeSlider.value;
        steeringValue.textContent = steeringSlider.value;

    } else{
        throttleSlider.min = window.CONFIG.control.parking.throttle.defaultMin;
        throttleSlider.max = window.CONFIG.control.parking.throttle.defaultMax;
        throttleSlider.step = window.CONFIG.control.parking.throttle.defaultStep;
        throttleSlider.value = window.CONFIG.control.parking.throttle.defaultInit;
        brakeSlider.min = window.CONFIG.control.parking.brake.defaultMin;
        brakeSlider.max = window.CONFIG.control.parking.brake.defaultMax;
        brakeSlider.step = window.CONFIG.control.parking.brake.defaultStep;
        brakeSlider.value = window.CONFIG.control.parking.brake.defaultInit;
        steeringSlider.min = window.CONFIG.control.parking.steering.defaultMin;
        steeringSlider.max = window.CONFIG.control.parking.steering.defaultMax;
        steeringSlider.step = window.CONFIG.control.parking.steering.defaultStep;
        steeringSlider.value = window.CONFIG.control.parking.steering.defaultInit;

        // 将配置文件的值填入配置输入框
        throttleMin.value = window.CONFIG.control.parking.throttle.defaultMin;
        throttleMax.value = window.CONFIG.control.parking.throttle.defaultMax;
        throttleStep.value = window.CONFIG.control.parking.throttle.defaultStep;
        throttleInit.value = window.CONFIG.control.parking.throttle.defaultInit;
        brakeMin.value = window.CONFIG.control.parking.brake.defaultMin;
        brakeMax.value = window.CONFIG.control.parking.brake.defaultMax;
        brakeStep.value = window.CONFIG.control.parking.brake.defaultStep;
        brakeInit.value = window.CONFIG.control.parking.brake.defaultInit;
        steeringMin.value = window.CONFIG.control.parking.steering.defaultMin;
        steeringMax.value = window.CONFIG.control.parking.steering.defaultMax;
        steeringStep.value = window.CONFIG.control.parking.steering.defaultStep;
        steeringInit.value = window.CONFIG.control.parking.steering.defaultInit;

        throttleValue.textContent = throttleSlider.value;
        brakeValue.textContent = brakeSlider.value;
        steeringValue.textContent = steeringSlider.value;

    }
}

switch_init();


/**
 * @brief 验证IP地址格式
 * @param {string} ip - IP地址字符串
 * @returns {boolean} - 是否为有效的IP地址
 */
function validateIPAddress(ip) {
    if (!ip || ip.trim() === '') {
        return false;
    }
    
    // IPv4地址正则表达式
    const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    
    // 支持localhost
    if (ip.toLowerCase() === 'localhost') {
        return true;
    }

    return ipv4Regex.test(ip) ;
}


/**
 * @brief 验证端口号
 * @param {string|number} port - 端口号
 * @returns {boolean} - 是否为有效的端口号
 */
function validatePort(port) {
    const portNum = parseInt(port);
    return !isNaN(portNum) && portNum >= 1 && portNum <= 65535;
}


// 更新图表信息
function updateChartData(statusData) {
    const data = statusData.html_report;
    if (window.ChartsAPI && window.ChartsAPI.isReady()) {

        window.ChartsAPI.addMultiData('comprehensive-chart', {
            '方向盘角度': data.steering_commend,
            '油门': data.throttle_commend,
            '刹车': data.brake_commend,
        });

        window.ChartsAPI.addData('chart-1', statusData.chassis.throttle.pedal_input );
        window.ChartsAPI.addData('chart-2',statusData.chassis.brake.pedal_input );
        window.ChartsAPI.addData('chart-3',statusData.chassis.steering.steering_wheel_torque_report);
        
    } else{
        console.log("图表未初始化");
    }
}

// ========== 车辆状态更新函数 ==========  

/**  
 * @brief 更新车辆状态显示  
 * @param {Object} statusData - 从WebSocket接收的状态数据  
 *   
 * 解析并显示车辆状态信息，包括：  
 * - 底盘状态（车速、方向盘、挡位、刹车、油门）  
 * - 车身状态（车门、灯光）  
 * - 控制状态（各控制器启用状态）  
 * - websocket系统状态（服务器状态、连接数）  
 */  
function updateVehicleStatusDisplay(statusData) {  
    try {  
        // ========== 更新底盘状态 ==========  
        if (statusData.chassis) {  
            const chassis = statusData.chassis;  
            
            // 更新车速  
            if (chassis.speed) {  
                const speed = chassis.speed.vehicle_speed;  
                const speedValid = chassis.speed.speed_valid;  
                statusSpeed.textContent = speedValid ?   
                    `${speed.toFixed(2)} m/s` :   
                    'N/A';  
                statusSpeed.className = speedValid ? 'status-value' : 'status-value status-invalid';  
            }  
            
            // 更新方向盘转角  
            if (chassis.steering) {  
                const angle = chassis.steering.angle;  
                const angleValid = chassis.steering.angle_valid;  
                statusSteeringAngle.textContent = angleValid ?   
                    `${angle.toFixed(1)}°` :   
                    'N/A';  
                statusSteeringAngle.className = angleValid ? 'status-value' : 'status-value status-invalid';  
            }  
            
            // 更新挡位  
            if (chassis.gear) {  
                const gear = chassis.gear.current_gear;  
                const gearValid = chassis.gear.gear_valid;  
                statusGear.textContent = gearValid ? gear : 'N/A';  
                statusGear.className = gearValid ? 'status-value' : 'status-value status-invalid';  

                if (gear==1)
                    statusGear.textContent = "P";
                else if (gear==2)
                    statusGear.textContent = "R";
                else if (gear==3)
                    statusGear.textContent = "N";
                else if (gear==4)
                    statusGear.textContent = "D";
                else
                    statusGear.textContent = "N/A";
            }  
            
            // 更新刹车踏板  
            if (chassis.brake) {  
                const brake = chassis.brake.brake_pedal;  
                const brakeValid = chassis.brake.brake_valid;  
                statusBrakePedal.textContent = brakeValid ?   
                    `${brake.toFixed(1)}%` :   
                    'N/A';  
                statusBrakePedal.className = brakeValid ? 'status-value' : 'status-value status-invalid';  
            }  
            
            // 更新油门踏板  
            if (chassis.throttle) {  
                const throttle = chassis.throttle.throttle_pedal;  
                const throttleValid = chassis.throttle.throttle_valid;  
                statusThrottlePedal.textContent = throttleValid ?   
                    `${throttle.toFixed(1)}%` :   
                    'N/A';  
                statusThrottlePedal.className = throttleValid ? 'status-value' : 'status-value status-invalid';  
            }  


            // 更新物理输入：油门
            throttleInput.textContent = chassis.throttle.pedal_input.toFixed(2);

            // 更新物理输入：刹车
            brakeInput.textContent = chassis.brake.pedal_input.toFixed(2);

            // 更新物理输入：方向盘
            steeringInput.textContent = chassis.steering.steering_wheel_torque_report.toFixed(2);

            // 更新物理输入：挡位
            if (chassis.gear.pedal_input==1)
                gearInput.textContent = "P";
            else if (chassis.gear.pedal_input==2)
                gearInput.textContent = "R";
            else if (chassis.gear.pedal_input==3)
                gearInput.textContent = "N";
            else if (chassis.gear.pedal_input==4)
                gearInput.textContent = "D";
            else
                gearInput.textContent = "N/A";
            
            // 更新程序输入：油门
            throttleCommand.textContent = chassis.throttle.command.toFixed(2);
            
            // 更新程序输入：刹车
            brakeCommand.textContent = chassis.brake.command.toFixed(2);;
            
            // 更新程序输入：方向盘
            steeringCommand.textContent = chassis.steering.command.toFixed(2);;

            // 更新程序输入：挡位
            gearCommand.textContent = chassis.gear.command;

            // 更新程序输入：挡位拒绝
            gearReject.textContent = chassis.gear.reject;

            // 更新接管状态：油门
            throttleOverride.textContent = chassis.throttle.override;   
            throttleOverride.className = chassis.throttle.override ? 'status-enabled' : 'status-disabled';

            // 更新接管状态：刹车
            brakeOverride.textContent = chassis.brake.override;   
            brakeOverride.className = chassis.brake.override ? 'status-enabled' : 'status-disabled';

            // 更新接管状态：方向盘
            steeringOverride.textContent = chassis.steering.override;   
            steeringOverride.className = chassis.steering.override ? 'status-enabled' : 'status-disabled';

            // 更新接管状态：挡位
            gearOverride.textContent = chassis.gear.override;   
            gearOverride.className = chassis.gear.override ? 'status-enabled' : 'status-disabled';

            // 更新握手状态: 油门
            throttleHandshake.textContent = chassis.throttle.ready;   
            throttleHandshake.className = chassis.throttle.ready ? 'status-enabled' : 'status-disabled';

            // 更新握手状态：刹车
            brakeHandshake.textContent = chassis.brake.ready;   
            brakeHandshake.className = chassis.brake.ready ? 'status-enabled' : 'status-disabled';


            // 更新握手状态：方向盘
            steeringHandshake.textContent = chassis.steering.ready;   
            steeringHandshake.className = chassis.steering.ready ? 'status-enabled' : 'status-disabled';


            // 更新握手状态：挡位
            gearHandshake.textContent = chassis.gear.ready;   
            gearHandshake.className = chassis.gear.ready ? 'status-enabled' : 'status-disabled';


        }  
        
        // ========== 更新前端控制指令 ==========  
        if (statusData.html_report) {  
            const controlStatus = statusData.html_report;  
            
            // 更新各控制器启用状态  
            if (controlStatus.throttle_enabled !== undefined) {  
                const throttle_value = controlStatus.throttle_commend;
                controlThrottleStatus.textContent = controlStatus.throttle_enabled ? parseFloat(throttle_value).toFixed(2) +' | 启用' : '-- | 禁用';  
                controlThrottleStatus.className = controlStatus.throttle_enabled ? 'status-enabled' : 'status-disabled';  
            }  
            
            if (controlStatus.brake_enabled !== undefined) {  
                const brake_value = controlStatus.brake_commend;
                controlBrakeStatus.textContent = controlStatus.brake_enabled ? parseFloat(brake_value).toFixed(2) +' | 启用' : '-- | 禁用';  
                controlBrakeStatus.className = controlStatus.brake_enabled ? 'status-enabled' : 'status-disabled';  
            }  
            
            if (controlStatus.steering_enabled !== undefined) {  
                const steering_value = controlStatus.steering_commend;
                controlSteeringStatus.textContent = controlStatus.steering_enabled ? parseFloat(steering_value).toFixed(2) +' | 启用' : '-- | 禁用';  
                controlSteeringStatus.className = controlStatus.steering_enabled ? 'status-enabled' : 'status-disabled';  
            }  
            
            if (controlStatus.gear_enabled !== undefined) {  
                const gear_value = controlStatus.gear_commend;
                controlGearStatus.textContent = controlStatus.gear_enabled ? gear_value +' | 启用' : '-- | 禁用';  
                controlGearStatus.className = controlStatus.gear_enabled ? 'status-enabled' : 'status-disabled';  
            }  
            
            // 更新驾驶模式  
            if (controlStatus.driving_mode !== undefined) {  
                if (controlStatus.driving_mode === "driving") {
                    controlDrivingMode.textContent = '行车';
                    controlDrivingMode.style.color = '#ff9800';  // 橙色  
                } else if (controlStatus.driving_mode === "parking") {
                    controlDrivingMode.textContent = '泊车';
                    controlDrivingMode.style.color = '#4CAF50';  // 绿色
                } else if (controlStatus.driving_mode === "none") {
                    controlDrivingMode.textContent = "手动";
                    controlDrivingMode.className = 'status-value';  
                } else {
                    controlDrivingMode.textContent = 'N/A';
                    controlDrivingMode.className = 'status-invalid'
                }
                
            }  
        }  
        
        // ========== 更新websocket系统状态 ==========  
        if (statusData.websocket_status) {  
            const systemStatus = statusData.websocket_status;  
            
            // 更新服务器状态  
            if (systemStatus.server_running !== undefined) {  
                serverStatus.textContent = systemStatus.server_running ? '在线' : '离线';  
                serverStatus.className = systemStatus.server_running ? 'status-enabled' : 'status-disabled';  
            }  
            
            // 更新连接客户端数量  
            if (systemStatus.connected_clients !== undefined) {  
                connectedClients.textContent = systemStatus.connected_clients.toString();  
                connectedClients.className = 'status-value';  
            }  

            // 更新面板模式
            if (systemStatus.panel_mode !== undefined) {  
                panelMode.textContent = systemStatus.panel_mode;  
                panelMode.className = 'status-value';  
            }  
        }  
        
        // ========== 更新通用信息 ==========  
        
        // 更新数据序号  
        if (statusData.seq !== undefined) {  
            dataSequence.textContent = statusData.seq.toString();  
        }  
        
        // 更新时间戳  
        if (statusData.timestamp !== undefined) {  
            const date = new Date(statusData.timestamp * 1000);  
            lastUpdate.textContent = date.toLocaleTimeString();  
        }  
        
    } catch (error) {  
        console.error('更新车辆状态显示时发生错误:', error);  
    }  
}  


// ========== WebSocket连接管理 ==========  

let socket;  // WebSocket连接对象  


        /**  
 * @brief 建立WebSocket连接  
 *   
 * 尝试连接到多个可能的服务器地址：  
 * 1. 10.21.103.150:8080 (指定的服务器地址)  
 * 2. localhost:8080 (本地环回)  
 * 3. 127.0.0.1:8080 (本地IP)  
 *   
 * 如果一个地址失败，自动尝试下一个地址  
 * 连接失败后会自动重连  
 */  
function connect() {  
    // 定义多个备选服务器地址  
    // const serverAddresses = [  
    //     'ws://10.21.162.157:8080'  // 主服务器地址  
    // ];  

    // 获取输入ip和端口
    const ip = ipAddressInput.value.trim();
    const port = portNumberInput.value.trim();

    // 验证输入
    if (!validateIPAddress(ip)) {
        connectStatusText.textContent = "无效输入";
        console.log("ip无效: ",ip);
        setTimeout(() => {connectStatusText.className = 'invalid'}, 100); // 闪一下
        connectStatusText.className = "disconnected"; 
        connectToggle.checked = false;
        ipInput.className = 'control-enabled'
        return;
    }
    if (!validatePort(port)) {
        connectStatusText.textContent = "无效输入";
        console.log("端口无效: ",port);
        setTimeout(() => {connectStatusText.className = 'invalid'}, 100); // 闪一下
        connectStatusText.className = "disconnected"; 
        connectToggle.checked = false;
        ipInput.className = 'control-enabled'
        return;
    }

    // connectStatusText.textContent = "已输入"

    const wsUrl = `ws://${ip}:${port}`;
    const serverAddresses = [
        wsUrl
    ];

            
    let currentAddressIndex = 0;  // 当前尝试的地址索引  
    
    /**  
     * @brief 尝试连接到当前索引的服务器地址  
     */  
    function tryConnect() {  
        // 如果所有地址都尝试失败，重置索引并延迟重连  
        if (currentAddressIndex >= serverAddresses.length) {  
            console.error("所有服务器地址都无法连接");  
            connectionStatus.textContent = "连接失败";  
            connectionStatus.className = "connection-status disconnected";  
            currentAddressIndex = 0;  // 重置索引  
            console.log("ip数量：",serverAddresses.length);
            setTimeout(connect, 2000);  // 2秒后重新尝试  
            return;  
        }  
        
        const wsUrl = serverAddresses[currentAddressIndex];  
        console.log(`尝试连接到: ${wsUrl}`);  
        connectionStatus.textContent = `连接中... (${wsUrl})`;  
        
        // 创建WebSocket连接  
        socket = new WebSocket(wsUrl);  
    
        /**  
         * @brief WebSocket连接成功事件处理  
         */  
        socket.onopen = function(e) {  
            console.log(`连接已建立: ${wsUrl}`);  
            isConnected = true;  
            connectStatusText.textContent = "已连接";
            connectStatusText.className = "connected";
            ipInput.className = 'control-disabled'
            connectionStatus.textContent = `已连接 (${wsUrl})`;  
            connectionStatus.className = "connection-status connected";  
        };  
        
        /**  
         * @brief WebSocket连接关闭事件处理  
         */  
        socket.onclose = function(e) {  
            console.log(`连接已关闭: ${wsUrl}`);  
            isConnected = false;  

            connectStatusText.textContent = "未连接";
            connectStatusText.className = "disconnected";
            ipInput.className = 'control-enabled'

            connectToggle.checked = false;
                
            connectionStatus.textContent = `连接中断 (${wsUrl})`;
            connectionStatus.className = "connection-status disconnected";  
            currentAddressIndex++;  // 尝试下一个地址  
        };  
        
        /**  
         * @brief WebSocket连接错误事件处理  
         */  
        socket.onerror = function(error) {  
            console.error(`WebSocket错误 (${wsUrl}):`, error);  
            currentAddressIndex++;  // 尝试下一个地址  
            connectionStatus.textContent = "连接中断"; 
        };  
        
        /**  
         * @brief WebSocket消息接收事件处理 
         *   
         * 处理来自C++后端的消息：  
         * - 控制命令确认  
         * - 车辆状态更新  
         * - 服务器状态信息  
         */  
        socket.onmessage = function(event) {  
            // TODO: 这里可以添加处理来自后端的状态更新消息  
            // 例如：实时显示车辆状态、处理服务器响应等  
            try {  
                const message = JSON.parse(event.data);  
                // console.log("收到消息:", message);      
                
                // 根据消息类型处理不同的消息  
                switch(message.type) {  
                    case 'vehicle_status':  
                        // 处理车辆状态消息  
                        updateVehicleStatusDisplay(message);  
                        updateChartData(message);
                        break;  
                        
                    case 'welcome':  
                        // 处理欢迎消息  
                        console.log('服务器欢迎消息:', message.message);  
                        break;  
                        
                    case 'received':  
                        // 处理控制命令确认消息  
                        console.log('控制命令已确认:', message.echo);  
                        break;  
                        
                    case 'error':  
                        // 处理错误消息  
                        console.error('服务器错误:', message.message);  
                        break;  
                        
                    default:  
                        console.log('未知消息类型:', message.type);  
                }  
            } catch (error) {  
                console.error('解析WebSocket消息时出错:', error);  
                console.log('原始消息:', event.data);  
            }  
        };  

    }  
    
    tryConnect();  // 开始尝试连接  
}  

// 页面加载时初始化连接取消，待输入完地址再请求链接
// connect();  


/**
* @brief 断开WebSocket连接
*/
function disconnect() {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close(1000, 'User disconnected'); // 正常关闭
    }
    
    socket = null;
    isConnected = false;
    // updateStatus('未连接', 'disconnected');

    connectStatusText.textContent = "未连接";

}

// ========== 数据发送功能 ==========  

/**  
    * @brief 发送控制数据到C++后端  
    *   
    * 构建包含所有控制信息的JSON对象并发送给后端：  
    * - 油门、刹车、方向盘、挡位、灯光的当前值  
    * - 各控制器的启用状态  
    * - 驾驶模式信息  
    * - 时间戳  
    */  
function sendControlData() {  
    if (!isConnected) return;  
    
    // 获取function请求控制的值
    const functionAction = parseInt(document.getElementById('function_action').value) || 0;
    const functionModuleType = parseInt(document.getElementById('function_module_type').value) || 0;
    const vsFunctionMode = parseInt(document.getElementById('vs_function_mode').value) || 0;
    
    // 构建控制数据对象  
    const controlData = {  
        // 面板的运行模式
        panel_mode: panelModeToggle.checked ? "control" : "display",
        // 控制值：如果控制器禁用，则发送0或安全值  
        throttle: enableStates.throttle ? parseFloat(throttleSlider.value) : 0.0,  
        brake: enableStates.brake ? parseFloat(brakeSlider.value) : 0.0,  
        steering: enableStates.steering ? parseFloat(steeringSlider.value) : 0.0,  
        gear: enableStates.gear ? currentGear : 'NONE',
        light: enableStates.light ? currentLight : 'NONE',
        front_light: enableStates.light ? currentFrontLight : 'OFF',  // 前灯状态
        
        // 时间戳  
        timestamp: Date.now(),  
        
        // 启用状态  
        enabled: enableStates,  
        
        // 数字模式数据
        throttle_number_mode: throttleNumberMode,
        brake_number_mode: brakeNumberMode,
        steering_number_mode: steeringNumberMode,

        // 驾驶模式  
        driving_mode: isDrivingMode,  
        mode_type: isDrivingMode ? "driving" : "parking",

        // 添加function请求控制数据
        function_control: {
            action: functionAction,
            module_type: functionModuleType
        },
        vs_request: {
            function_mode: vsFunctionMode
        }
    };  
    
    // 发送JSON数据到后端  
    socket.send(JSON.stringify(controlData));  
}  

// ========== 控制器启用/禁用管理 ==========  

/**  
* @brief 切换指定控制器的启用状态  
* @param controlType 控制器类型 ('throttle', 'brake', 'steering', 'gear','epb','epb_cmd')  
*/  
function toggleControl(controlType) {  
    enableStates[controlType] = !enableStates[controlType];  // 切换状态  
    updateControlUI(controlType);  // 更新UI显示  
    sendControlData();  // 发送更新后的数据  
}  

/**  
    * @brief 更新控制器的UI显示状态  
    * @param controlType 控制器类型  ('throttle', 'brake', 'steering', 'gear','epb','epb_cmd')  
    *   
    * 根据启用状态更新：  
    * - 按钮文本和颜色  
    * - 控制区域的可用性  
    * - 禁用时重置控制值  
    */  
function updateControlUI(controlType) {  
    const isEnabled = enableStates[controlType];  
    switch(controlType) {  
        case 'epb':
            // 更新EPB控制UI
            if (epbEnable) {
                epbEnable.textContent = isEnabled ? 'EPB已启用' : 'EPB已禁用';
                epbEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;
                if (epbControls) {
                    epbControls.className = isEnabled ? '' : 'control-disabled';
                }
            }
            break;
            
        case 'epb_cmd':
            // 更新EPB命令控制UI
            if (epbCmd) {
                epbCmd.textContent = isEnabled ? 'EPB命令已启用' : 'EPB命令已禁用';
                epbCmd.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;
                if (epbCmdControls) {
                    epbCmdControls.className = isEnabled ? '' : 'control-disabled';
                }
            }
            break;

        case 'throttle':  
            // 更新油门控制UI  
            throttleEnable.textContent = isEnabled ? '油门已启用' : '油门已禁用';  
            throttleEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;  
            throttleControls.className = isEnabled ? '' : 'control-disabled';  
            
            // 禁用时重置为0  
            if (!isEnabled) {  
                throttleSlider.value = isDrivingMode? window.CONFIG.control.driving.throttle.defaultInit:window.CONFIG.control.parking.throttle.defaultInit ;  
                throttleValue.textContent = isDrivingMode? window.CONFIG.control.driving.throttle.defaultInit:window.CONFIG.control.parking.throttle.defaultInit ;  
            }  
            break;  
            
        case 'brake':  
            // 更新刹车控制UI  
            brakeEnable.textContent = isEnabled ? '刹车已启用' : '刹车已禁用';  
            brakeEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;  
            brakeControls.className = isEnabled ? '' : 'control-disabled';
            
            // 禁用时重置为0  
            if (!isEnabled) {  
                brakeSlider.value = isDrivingMode? window.CONFIG.control.driving.brake.defaultInit:window.CONFIG.control.parking.brake.defaultInit ;  
                brakeValue.textContent = isDrivingMode? window.CONFIG.control.driving.brake.defaultInit:window.CONFIG.control.parking.brake.defaultInit ;  

            }  
            break;  
            
        case 'steering':  
            // 更新方向盘控制UI  
            steeringEnable.textContent = isEnabled ? '方向盘已启用' : '方向盘已禁用';  
            steeringEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;  
            steeringControls.className = isEnabled ? '' : 'control-disabled';  
            
            // 禁用时重置为中央位置  
            if (!isEnabled) {  
                steeringSlider.value = isDrivingMode? window.CONFIG.control.driving.steering.defaultInit:window.CONFIG.control.parking.steering.defaultInit ;  
                steeringValue.textContent = isDrivingMode? window.CONFIG.control.driving.steering.defaultInit:window.CONFIG.control.parking.steering.defaultInit ;  
            }  
            break;  
            
        case 'gear':  
            // 更新挡位控制UI  
            gearEnable.textContent = isEnabled ? '挡位已启用' : '挡位已禁用';  
            gearEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;  
            gearControls.className = isEnabled ? '' : 'control-disabled';  

            // 禁用时重置为NONE挡  
            if (!isEnabled) {  
                gearButtons[currentGear].classList.remove('active');  
                currentGear = 'NONE';  
                gearButtons['NONE'].classList.add('active');  
                gearValue.textContent = 'NONE';  
            }  
            break;

        case 'light':
            // 更新灯光控制UI
            lightEnable.textContent = isEnabled ? '灯光已启用' : '灯光已禁用';
            lightEnable.className = `enable-button ${isEnabled ? 'enabled' : 'disabled'}`;
            lightControls.className = isEnabled ? '' : 'control-disabled';
            
            // 禁用时重置为NONE
            if (!isEnabled) {
                if (lightButtons[currentLight]) {
                    lightButtons[currentLight].classList.remove('active');
                }
                currentLight = 'NONE';
                if (lightButtons['NONE']) {
                    lightButtons['NONE'].classList.add('active');
                }
                lightValue.textContent = 'NONE';

                if (frontLightButtons[currentFrontLight]) {
                    frontLightButtons[currentFrontLight].classList.remove('active');
                }
                currentFrontLight = 'OFF';
                if (frontLightButtons['OFF']) {
                    frontLightButtons['OFF'].classList.add('active');
                }
                frontLightValue.textContent = 'OFF';
            }
            break;
    }  
}  

/**  
    * @brief 更新泊车状态显示  
    *   
    * 根据当前挡位显示车辆状态：  
    * - P挡或NONE挡：显示"已泊车"（绿色）  
    * - 其他挡位：显示"行驶中"（橙色）  
    */  
function updateParkingStatus() {  
    if (currentGear === 'P' || currentGear === 'NONE') {  
        parkingStatus.textContent = '已泊车';  
        parkingStatus.style.color = '#4CAF50';  // 绿色  
    } else {  
        parkingStatus.textContent = '行驶中';  
        parkingStatus.style.color = '#ff9800';  // 橙色  
    }  
}  

// ========== 驾驶模式管理 ==========  

// ========== 泊车状态管理 ==========
let parkingStatus = 'in_progress'; // 'in_progress' 或 'completed'

// 获取泊车状态按钮
const parkingInProgressBtn = document.getElementById('parking-in-progress');
const parkingCompletedBtn = document.getElementById('parking-completed');
const parkingStatusSelector = document.getElementById('parking-status-selector');

// 泊车状态切换函数
function setParkingStatus(status) {
    parkingStatus = status;
    
    // 更新按钮样式
    parkingInProgressBtn.classList.toggle('active', status === 'in_progress');
    parkingCompletedBtn.classList.toggle('active', status === 'completed');
    
    console.log(`泊车状态设置为: ${status === 'in_progress' ? '泊入进行中' : '泊入完成'}`);
    
    // 发送状态到后端
    sendParkingStatus();
}

// 绑定按钮点击事件
parkingInProgressBtn.addEventListener('click', () => setParkingStatus('in_progress'));
parkingCompletedBtn.addEventListener('click', () => setParkingStatus('completed'));


/**  
    * @brief 切换驾驶模式  
    *   
    * 在泊车模式和行车模式之间切换：  
    * - 泊车模式：用于停车、泊车辅助等低速操作  
    * - 行车模式：用于正常驾驶  
    */  
function toggleDriveMode() {  
    isDrivingMode = !isDrivingMode;  // 切换模式  

    switch_init();
    
    if (isDrivingMode) {  
        // 切换行车模式  
        driveMode.textContent = '行车模式';  
        driveMode.style.color = '#ff9800';  // 橙色  
        modeToggleBtn.textContent = '切换泊车模式';  
        modeToggleBtn.style.backgroundColor = '#ff9800';  
        modeDescription.textContent = '车辆可正常行驶，所有控制功能可用';  

        // 隐藏泊车状态选择器
        parkingStatusSelector.style.display = 'none';
    } else {  
        // 切换泊车模式  
        driveMode.textContent = '泊车模式';  
        driveMode.style.color = '#4CAF50';  // 绿色  
        modeToggleBtn.textContent = '切换行车模式';  
        modeToggleBtn.style.backgroundColor = '#4CAF50';  
        modeDescription.textContent = '车辆已停止，可进行泊车操作';  

            // 显示泊车状态选择器
        parkingStatusSelector.style.display = 'block';
        
        // 设置默认泊入进行中状态
        setParkingStatus('in_progress');
    }  
    
    sendControlData();  // 发送模式更新  
}  

// ========== 发送泊车状态到后端 ==========
function sendParkingStatus() {
    if (!isConnected) return;
    
    const parkingData = {
        type: 'parking_status',
        status: parkingStatus,
        timestamp: Date.now()
    };
    
    socket.send(JSON.stringify(parkingData));
    console.log('发送泊车状态:', parkingStatus);
}


// ========== 控制器事件监听 ==========  

/**  
    * @brief 油门滑块事件监听  
    * 当用户拖动油门滑块时触发  
    */  
throttleSlider.addEventListener('input', function() {  
    if (!enableStates.throttle) return;  // 禁用时不响应  
    throttleValue.textContent = parseFloat(this.value).toFixed(2);  // 更新显示值  
    sendControlData();  // 发送数据  
});  

/**  
    * @brief 刹车滑块事件监听  
    * 当用户拖动刹车滑块时触发  
    */  
brakeSlider.addEventListener('input', function() {  
    if (!enableStates.brake) return;  // 禁用时不响应  
    brakeValue.textContent = parseFloat(this.value).toFixed(2);  // 更新显示值  
    sendControlData();  // 发送数据  
});  

/**  
    * @brief 方向盘滑块事件监听  
    * 当用户拖动方向盘滑块时触发  
    */  
steeringSlider.addEventListener('input', function() {  
    if (!enableStates.steering) return;  // 禁用时不响应  
    const value = parseFloat(this.value);  
    steeringValue.textContent = value.toFixed(2);  // 更新显示值    
    sendControlData();  // 发送数据  
});  

/**  
    * @brief 挡位按钮事件监听  
    * 为每个挡位按钮添加点击事件  
    */  
Object.keys(gearButtons).forEach(gear => {  
    gearButtons[gear].addEventListener('click', function() {  
        // 禁用时或点击当前挡位时不响应  
        if (!enableStates.gear || currentGear === gear) return;  
        
        // 更新挡位显示  
        gearButtons[currentGear].classList.remove('active');  // 移除当前挡位的激活状态  
        this.classList.add('active');  // 激活新挡位  
        currentGear = gear;  // 更新当前挡位  
        gearValue.textContent = gear;  // 更新显示  
        // updateParkingStatus();  // 更新泊车状态  
        
        sendControlData();  // 发送数据  
    });  
});  

/**  
    * @brief 灯光按钮事件监听  
    * 为每个灯光按钮添加点击事件  
    */  
Object.keys(lightButtons).forEach(light => {  
    lightButtons[light].addEventListener('click', function() {  
        // 禁用时或点击当前灯光时不响应  
        if (!enableStates.light || currentLight === light) return;  
        
        // 更新灯光显示  
        lightButtons[currentLight].classList.remove('active');  // 移除当前灯光的激活状态  
        this.classList.add('active');  // 激活新灯光  
        currentLight = light;  // 更新当前灯光  
        lightValue.textContent = light;  // 更新显示  
        
        sendControlData();  // 发送数据  
    });  
});


/**
 * @brief 为配置保存按钮添加点击事件
 * 
 */
configSaveButten.addEventListener('click', function() {
    // 若是启用状态,则退出
    if (enableStates.throttle){
        alert('禁用油门后修改');
        return;
    }

    let minValue = parseFloat(throttleMin.value) ;
    let maxValue = parseFloat(throttleMax.value) ;
    let stepValue = parseFloat(throttleStep.value) ;
    let initValue = parseFloat(throttleInit.value) ;

    // 验证输入
    if (minValue >= maxValue || stepValue <= 0 || initValue < minValue || initValue > maxValue) {
        alert('请输入有效的范围和初始值');
        return;
    }
    throttleMin.value = minValue;
    throttleMax.value = maxValue;
    throttleStep.value = stepValue;
    throttleInit.value = initValue;

    // 更新滑杆和控制值
    throttleSlider.min = minValue;
    throttleSlider.max = maxValue;
    throttleSlider.step = stepValue;
    throttleSlider.value = initValue;
    throttleValue.value = initValue;
    throttleValue.textContent = initValue; 

    // 更新全局配置值
    updateGlobalConfig('throttle', minValue, maxValue, stepValue, initValue);


    // 若是启用状态,则退出
    if (enableStates.brake){
        alert('禁用刹车后修改');
        return;
    }

    minValue = parseFloat(brakeMin.value) ;
    maxValue = parseFloat(brakeMax.value) ;
    stepValue = parseFloat(brakeStep.value) ;
    initValue = parseFloat(brakeInit.value) ;

    // 验证输入
    if (minValue >= maxValue || stepValue <= 0 || initValue < minValue || initValue > maxValue) {
        alert('请输入有效的范围和初始值');
        return;
    }
    brakeMin.value = minValue;
    brakeMax.value = maxValue;
    brakeStep.value = stepValue;
    brakeInit.value = initValue;

    // 更新滑杆和控制值
    brakeSlider.min = minValue;
    brakeSlider.max = maxValue;
    brakeSlider.step = stepValue;
    brakeSlider.value = initValue;
    brakeValue.value = initValue;
    brakeValue.textContent = initValue; 

    updateGlobalConfig('brake', minValue, maxValue, stepValue, initValue);


    // 若是启用状态,则退出
    if (enableStates.steering){
        alert('禁用方向盘后修改');
        return;
    }

    minValue = parseFloat(steeringMin.value) ;
    maxValue = parseFloat(steeringMax.value) ;
    stepValue = parseFloat(steeringStep.value) ;
    initValue = parseFloat(steeringInit.value) ;

    // 验证输入
    if (minValue >= maxValue || stepValue <= 0 || initValue < minValue || initValue > maxValue) {
        alert('请输入有效的范围和初始值');
        return;
    }
    steeringMin.value = minValue;
    steeringMax.value = maxValue;
    steeringStep.value = stepValue;
    steeringInit.value = initValue;

    // 更新滑杆和控制值
    steeringSlider.min = minValue;
    steeringSlider.max = maxValue;
    steeringSlider.step = stepValue;
    steeringSlider.value = initValue;
    steeringValue.value = initValue;
    steeringValue.textContent = initValue; 

    updateGlobalConfig('steering', minValue, maxValue, stepValue, initValue);
});


function updateGlobalConfig(controlType, min, max, step, init) {
    if (isDrivingMode) {
        window.CONFIG.control.driving[controlType].defaultMin = min;
        window.CONFIG.control.driving[controlType].defaultMax = max;
        window.CONFIG.control.driving[controlType].defaultStep = step;
        window.CONFIG.control.driving[controlType].defaultInit = init;
    } else {
        window.CONFIG.control.parking[controlType].defaultMin = min;
        window.CONFIG.control.parking[controlType].defaultMax = max;
        window.CONFIG.control.parking[controlType].defaultStep = step;
        window.CONFIG.control.parking[controlType].defaultInit = init;
    }
}


function updateSliderAndText(Slider,Value,min,max,step,init){
    Slider.min = min;
    Slider.max = max;
    Slider.step = step;
    Slider.value = init;
    Value.value = init;
    Value.textContent = init; 
}


Object.keys(frontLightButtons).forEach(frontLight => {
    frontLightButtons[frontLight].addEventListener('click', function() {
        // 禁用时或点击当前前灯时不响应  
        if (!enableStates.light || currentFrontLight === frontLight) return;  
        
        // 更新前灯显示  
        frontLightButtons[currentFrontLight].classList.remove('active');
        this.classList.add('active');  // 激活新前灯  
        currentFrontLight = frontLight;  // 更新当前前灯  
        frontLightValue.textContent = frontLight;  // 更新显示  
        
        sendControlData();  // 发送数据  
    });
});

// 获取当前所有数字模式值
function getAllNumberModeValues() {
    return {
        throttle_number_mode: throttleNumberMode,
        brake_number_mode: brakeNumberMode,
        steering_number_mode: steeringNumberMode
    };
}

// 重置所有数字模式值
function resetAllNumberModes() {
    throttleNumberMode = 0;
    brakeNumberMode = 0;
    steeringNumberMode = 0;
    
    // 重置输入框显示
    const throttleInput = document.getElementById('throttle-number');
    const brakeInput = document.getElementById('brake-number');
    const steeringInput = document.getElementById('steering-number');
    
    if (throttleInput) throttleInput.value = 0;
    if (brakeInput) brakeInput.value = 0;
    if (steeringInput) steeringInput.value = 0;
    
    console.log('所有数字模式值已重置');
    
    // 发送重置后的数据
    sendControlData();
}

// 设置数字模式值（用于外部调用）
function setNumberModeValue(controlType, value) {
    const numberInput = document.getElementById(`${controlType}-number`);
    if (numberInput) {
        numberInput.value = value;
        
        // 更新对应的变量
        switch(controlType) {
            case 'throttle':
                throttleNumberMode = value;
                break;
            case 'brake':
                brakeNumberMode = value;
                break;
            case 'steering':
                steeringNumberMode = value;
                break;
        }
        
        console.log(`${controlType} 数字模式值设置为: ${value}`);
        sendControlData();
    }
}

// ========== 其他事件监听 ==========  

// 驾驶模式切换按钮事件  
modeToggleBtn.addEventListener('click', toggleDriveMode);  

// 各控制器启用/禁用按钮事件  
throttleEnable.addEventListener('click', () => toggleControl('throttle'));  
brakeEnable.addEventListener('click', () => toggleControl('brake'));  
steeringEnable.addEventListener('click', () => toggleControl('steering'));  
gearEnable.addEventListener('click', () => toggleControl('gear'));
lightEnable.addEventListener('click', () => toggleControl('light'));
epbEnable.addEventListener('click', () => toggleControl('epb'));
epbCmd.addEventListener('click', () => toggleControl('epb_cmd'));

// connectButton.addEventListener('click',  function() {if (!isConnected) {connect();}});

// ========== 定时数据发送 ==========

/**
    * @brief 定期发送控制数据
    * 
    * 每100毫秒发送一次控制数据到后端，确保：
    * - 实时性：后端能及时收到最新的控制状态
    * - 心跳机制：保持连接活跃
    * - 状态同步：确保前后端状态一致
    */
setInterval(sendControlData, 100);


// ========== 全局控制按钮 ==========

/**
* @brief 启用全部控制按钮
* 一键启用所有控制器（油门、刹车、方向盘、挡位）
*/
enableAllBtn = document.getElementById("enable-all-btn");
enableAllBtn.textContent = '全部启用';
enableAllBtn.style.cssText = `
    padding: 5px 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
`;
enableAllBtn.addEventListener('click', () => {
    // 启用所有控制器
    Object.keys(enableStates).forEach(control => {
        enableStates[control] = true;
        updateControlUI(control);
    });
    sendControlData();
});

/**
* @brief 紧急停止按钮
* 一键禁用所有控制器，用于紧急情况
*/
disableAllBtn = document.getElementById("disable-all-btn");
disableAllBtn.textContent = '紧急停止';
disableAllBtn.style.cssText = `
    padding: 5px 10px;
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
`;
disableAllBtn.addEventListener('click', () => {
    // 禁用所有控制器
    Object.keys(enableStates).forEach(control => {
        enableStates[control] = false;
        updateControlUI(control);
    });
    sendControlData();
});


// 添加连接开关按钮的触发事件
connectToggle.addEventListener('change', function() {
    if (this.checked) {
        connect();
    } else {
        disconnect();
    }
});

// 添加面板模式按钮的触发事件
panelModeToggle.addEventListener('change', function() {
    if (this.checked) {
        switch_init();
        panelModeText.textContent = "控制";
    } else {
        switch_init();
        panelModeText.textContent = "展示";
    }
});




// ========== 键盘控制功能 ==========

/**
    * @brief 键盘按键状态跟踪
    * 
    * 使用对象来跟踪当前按下的按键，支持多键同时按下
    * 这样可以实现更流畅的键盘控制体验
    */
const keysPressed = {};
let keyControlInterval = null;  // 键盘控制循环的定时器

/**
    * @brief 键盘按下事件处理
    * 
    * 监听以下按键：
    * - W/S: 控制油门
    * - A/D: 控制刹车  
    * - 左箭头/右箭头: 控制方向盘
    */
document.addEventListener('keydown', function(event) {
    const key = event.key.toLowerCase();
    // 只处理车辆控制相关的按键
    if (['w', 's', 'a', 'd', 'arrowleft', 'arrowright'].includes(key)) {
        event.preventDefault();  // 阻止默认行为（如页面滚动）
        keysPressed[key] = true;  // 标记按键为按下状态
    }
});

/**
    * @brief 键盘释放事件处理
    * 
    * 当按键释放时，从按键状态中移除对应的按键
    */
document.addEventListener('keyup', function(event) {
    const key = event.key.toLowerCase();
    if (['w', 's', 'a', 'd', 'arrowleft', 'arrowright'].includes(key)) {
        event.preventDefault();
        delete keysPressed[key];  // 移除按键状态
    }
});

/**
    * @brief 更新车辆控制状态
    * 
    * 根据当前按下的按键更新车辆控制状态：
    * - 自动启用相应的控制器
    * - 根据按键调整控制值
    * - 提供平滑的控制体验
    */
function updateVehicleState() {
    let stateChanged = false;

    // ========== 油门控制 (W/S键) ==========
    if (keysPressed['w']) {
        // W键：增加油门
        if (!enableStates.throttle) { 
            enableStates.throttle = true; 
            updateControlUI('throttle'); 
        }
        const currentValue = parseFloat(throttleSlider.value);
        const newValue = Math.min(currentValue + parseFloat(throttleSlider.step), 4);
        throttleSlider.value = newValue;
        throttleValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    } else if (keysPressed['s']) {
        // S键：减少油门
        if (!enableStates.throttle) { 
            enableStates.throttle = true; 
            updateControlUI('throttle'); 
        }
        const currentValue = parseFloat(throttleSlider.value);
        const newValue = Math.max(currentValue - parseFloat(throttleSlider.step), 0);
        throttleSlider.value = newValue;
        throttleValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    }

    // ========== 刹车控制 (A/D键) ==========
    if (keysPressed['d']) {
        // D键：增加刹车
        if (!enableStates.brake) { 
            enableStates.brake = true; 
            updateControlUI('brake'); 
        }
        const currentValue = parseFloat(brakeSlider.value);
        const newValue = Math.min(currentValue + parseFloat(brakeSlider.step), 4);
        brakeSlider.value = newValue;
        brakeValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    } else if (keysPressed['a']) {
        // A键：减少刹车
        if (!enableStates.brake) { 
            enableStates.brake = true; 
            updateControlUI('brake'); 
        }
        const currentValue = parseFloat(brakeSlider.value);
        const newValue = Math.max(currentValue - parseFloat(brakeSlider.step), -3);
        brakeSlider.value = newValue;
        brakeValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    }

    // ========== 方向盘控制 (左右箭头键) ==========
    if (keysPressed['arrowright']) {
        // 右箭头：向右转
        if (!enableStates.steering) { 
            enableStates.steering = true; 
            updateControlUI('steering'); 
        }
        const currentValue = parseFloat(steeringSlider.value);
        const newValue = Math.min(currentValue + parseFloat(steeringSlider.step), 1);
        steeringSlider.value = newValue;
        steeringValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    } else if (keysPressed['arrowleft']) {
        // 左箭头：向左转
        if (!enableStates.steering) { 
            enableStates.steering = true; 
            updateControlUI('steering'); 
        }
        const currentValue = parseFloat(steeringSlider.value);
        const newValue = Math.max(currentValue - parseFloat(steeringSlider.step), -1);
        steeringSlider.value = newValue;
        steeringValue.textContent = newValue.toFixed(2);
        stateChanged = true;
    }

    // 如果有状态变化，发送控制数据
    if (stateChanged) {
        sendControlData();
    }
}

/**
    * @brief 启动键盘控制循环
    * 
    * 每50毫秒检查一次键盘状态并更新车辆控制
    * 这个频率确保了响应的实时性和流畅性
    */
keyControlInterval = setInterval(updateVehicleState, 50);

// ========== 快捷禁用功能 ==========

/**
    * @brief Q/E键快捷禁用功能
    * 
    * 提供快速禁用控制器的功能：
    * - Q键：禁用油门控制
    * - E键：禁用刹车控制
    * - G键：禁用所有
    * 
    * 这些快捷键在紧急情况下特别有用
    */
document.addEventListener('keydown', function(event) {
    // 防止方向键等导致页面滚动
    if(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'w', 'a', 's', 'd', 'W', 'A', 'S', 'D'].includes(event.key)) {
        // 这个处理已经在上面的监听器中完成
    }
    
    const key = event.key.toLowerCase();
    if (key === 'q') {
        // Q键：禁用油门
        if (enableStates.throttle) {
            enableStates.throttle = false;
            updateControlUI('throttle');
            sendControlData();
        }
    } else if (key === 'e') {
        // E键：禁用刹车
        if (enableStates.brake) {
            enableStates.brake = false;
            updateControlUI('brake');
            sendControlData();
        }
    } else if (key== 'g') {
        // G键：禁用所有
        if (enableStates.throttle || enableStates.brake || enableStates.steering) {
            enableStates.throttle = false;
            enableStates.brake = false;
            enableStates.steering = false;
            enableStates.gear = false;
            updateControlUI('throttle');
            updateControlUI('brake');
            updateControlUI('steering');
            updateControlUI('gear');
            updateControlUI('epb');
            updateControlUI('epb_cmd');
            sendControlData();
        }
    }
});



// ========== 页面生命周期管理 ==========

// 页面加载完成后的初始化
window.addEventListener('DOMContentLoaded', () => {
    // 初始化数字模式变量
    throttleNumberMode = 0;
    brakeNumberMode = 0;
    steeringNumberMode = 0;
    
    // 初始化独立的数字输入框模式（替换原有的初始化）
    initNumberInputMode();

    // 初始化控制值的数字框输入
    initNumberInputCmd();
    
    // 根据初始驾驶模式状态决定是否显示泊车状态选择器
    if (isDrivingMode) {
        // 行车模式：隐藏泊车状态选择器
        parkingStatusSelector.style.display = 'none';
    } else {
        // 泊车模式：显示泊车状态选择器并设置默认状态
        parkingStatusSelector.style.display = 'block';
        // 延迟一点发送，确保WebSocket连接已建立
        setTimeout(() => {
            setParkingStatus('in_progress');
        }, 1000);
    }
});

/**
    * @brief 页面关闭时的清理工作
    * 
    * 在用户关闭页面或刷新页面时：
    * - 清除定时器
    * - 关闭WebSocket连接
    * - 防止内存泄漏
    */
window.addEventListener('beforeunload', function() {
    // 清除键盘控制定时器
    if (keyControlInterval) {
        clearInterval(keyControlInterval);
    }
    
    // 关闭WebSocket连接
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
    }
});

// ========== 错误处理和调试 ==========

/**
    * @brief 全局错误处理
    * 
    * 捕获JavaScript运行时错误，防止页面崩溃
    */
window.addEventListener('error', function(event) {
    console.error('页面发生错误:', event.error);
    // 可以在这里添加错误上报或用户提示
});

/**
    * @brief 调试信息输出
    * 
    * 在开发模式下输出调试信息
    */
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    console.log('车辆控制面板已加载');
    console.log('支持的控制方式:');
    console.log('- 鼠标/触摸：拖动滑块和点击按钮');
    console.log('- 键盘：W/S(油门), A/D(刹车), ←/→(方向盘), Q/E(禁用)');
    console.log('- 全局控制：启用全部控制、紧急停止');
}